package com.hro.rickpimines.project4.vogelspot1;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

public class VogelFotoActivity extends Activity implements LocationListener
{
	private static final int CAMERA_REQUEST = 1888;
	private ImageView imageView;
	private Uri mImageUri;
	private File photo;
	private Spinner spinner;

	private String newFoto = "";
	private String naam = "";
	
	private String latDMS;
	private String lngDMS;

	public static final String TAG = "VogelFotoActivity: ";
	public static final int VOGEL_IMAGE = 1;

	public ArrayList<String> galleryList = new ArrayList<String>();

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.vogelfotoactivity);

		FillPhotoList();
		
		spinner = (Spinner) findViewById(R.id.spinner1);

		populateSpinner();
		

		LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 10.0f,
		        this);

		lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000L,
		        10.0f, this);

		Location location = lm
		        .getLastKnownLocation(LocationManager.GPS_PROVIDER);

		if (location != null) {
			Log.v(TAG, "Latitude: " + location.getLatitude() + ",Longitude: "
			        + location.getLongitude());

			latDMS = decimalToDMS(location.getLatitude());
			lngDMS = decimalToDMS(location.getLongitude());
		}

		imageView = (ImageView) this.findViewById(R.id.imageView1);
	}

	public void takePhoto(View view)
	{
		Intent intent = new Intent(
		        android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

		try {
			// place where to store camera taken picture
			photo = this.createTemporaryFile("picture", ".jpg");
			photo.delete();
		} catch (Exception e) {
			Log.v(TAG, "Can't create file to take picture!");
			Toast.makeText(this,
			        "Please check SD card! Image shot is impossible!", 10000);
		}

		mImageUri = Uri.fromFile(photo);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
		// start camera intent
		this.startActivityForResult(intent, VOGEL_IMAGE);

	}

	/*
	 * public void onActivityResult(int requestCode, int resultCode, Intent
	 * intent) { super.onActivityResult(requestCode, resultCode, intent); if
	 * (resultCode == RESULT_OK) { Bitmap bitmap; try { bitmap =
	 * this.grabImage(imageView); imageView.setImageBitmap(bitmap);
	 * 
	 * Toast.makeText(this, "", 10000);
	 * 
	 * } catch (Exception e) { e.printStackTrace(); } } }
	 */

	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if (requestCode == VOGEL_IMAGE) {
			// based on the result we either set the preview or show a quick
			// toast splash.
			if (resultCode == RESULT_OK) {
				// This is ##### ridiculous. Some versions of Android save
				// to the MediaStore as well. Not sure why! We don't know what
				// name Android will give either, so we get to search for this
				// manually and remove it.
				String[] projection = { MediaStore.Images.ImageColumns.SIZE,
				        MediaStore.Images.ImageColumns.DISPLAY_NAME,
				        MediaStore.Images.ImageColumns.DATA, BaseColumns._ID, };
				//
				// intialize the Uri and the Cursor, and the current expected
				// size.
				Cursor c = null;
				Uri u = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				//
				if (photo != null) {
					// Query the Uri to get the data path. Only if the Uri is
					// valid,
					// and we had a valid size to be searching for.
					if ((u != null) && (photo.length() > 0)) {
						c = managedQuery(u, projection, null, null, null);
					}
					//
					// If we found the cursor and found a record in it (we also
					// have the size).
					if ((c != null) && (c.moveToFirst())) {
						do {
							// Check each area in the gallary we built before.
							boolean bFound = false;
							for (String sGallery : galleryList) {
								if (sGallery.equalsIgnoreCase(c.getString(1))) {
									bFound = true;
									break;
								}
							}
							//
							// To here we looped the full gallery.
							if (!bFound) {
								// This is the NEW image. If the size is bigger,
								// copy it.
								// Then delete it!
								// File f = new File(c.getString(2));

								Log.v(TAG, "foto gevonden, naar showNewPhoto");
								newFoto = c.getString(2);
								showNewPhoto();

								break;
							}
						} while (c.moveToNext());
					}
				}
			}
		}
	}

	private void showNewPhoto()
	{
		Button captureFront = (Button) findViewById(R.id.captureFront);
		captureFront.setVisibility(View.INVISIBLE);

		Bitmap bitmap = BitmapFactory.decodeFile(newFoto);
		imageView.setImageBitmap(bitmap);

		spinner.setVisibility(View.VISIBLE);

		Button button1 = (Button) findViewById(R.id.button1);
		button1.setVisibility(View.VISIBLE);

		spinner.setOnItemSelectedListener(new OnItemSelectedListener()
		{

			public void onItemSelected(AdapterView<?> parentView,
			        View selectedItemView, int position, long id)
			{
				String vogel = (String) spinner.getItemAtPosition(position);

				if (!vogel.toLowerCase().contains(" ")) {
					naam = vogel;
				}

			}

			public void onNothingSelected(AdapterView<?> parentView)
			{
				// your code here
			}

		});
		
		
		
		button1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	uploadFoto();
            }
        });
	}
	//<!-- android:icon="@drawable/ic_launcher"-->
	public void uploadFoto()
	{
		ExifInterface exif;
		try {
			exif = new ExifInterface(newFoto);

			Log.v(TAG, newFoto);

			Log.v(TAG, "latDMS: " + latDMS + ", lngDMS: " + lngDMS);

			exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE, latDMS);
			exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, lngDMS);
			exif.setAttribute(ExifInterface.TAG_MAKE, naam);

			exif.saveAttributes();

			Log.v(TAG, "exif data gefixt");

			Uploader uploader = new Uploader();

			Log.v(TAG, "we gaan proberen te uploaden");
			uploader.upload(newFoto);
			Toast.makeText(this, "De foto van de "+ naam + "is geupload",
			        100000).show();
			startActivity(new Intent (this, VogelSpotActivity.class));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void populateSpinner()
	{
		Vogels v = new Vogels();
		ArrayList<String> list = new ArrayList<String>();
		list.add("Geen selectie");

		for (String vogelNaam : v.getVogelNamen()) {
			list.add(vogelNaam);
		}

		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
		        android.R.layout.simple_spinner_item, list);
		dataAdapter
		        .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(dataAdapter);
	}

	private File createTemporaryFile(String part, String ext) throws Exception
	{
		File tempDir = Environment.getExternalStorageDirectory();
		tempDir = new File(tempDir.getAbsolutePath() + "/.temp/");
		if (!tempDir.exists()) {
			tempDir.mkdir();
		}
		return File.createTempFile(part, ext, tempDir);
	}

	public Bitmap grabImage(ImageView imageView) throws FileNotFoundException,
	        IOException
	{
		this.getContentResolver().notifyChange(mImageUri, null);
		ContentResolver cr = this.getContentResolver();

		mImageUri = Uri.fromFile(photo);
		return android.provider.MediaStore.Images.Media
		        .getBitmap(cr, mImageUri);

	}

	String decimalToDMS(double coord)
	{
		String output, degrees, minutes;

		double mod = coord % 1;
		int intPart = (int) coord;

		degrees = String.valueOf(intPart);

		coord = mod * 60;
		mod = coord % 1;
		intPart = (int) coord;
		minutes = String.valueOf(intPart);

		coord = mod * 60;

		output = degrees + "/1," + minutes + "/1,"
		        + Integer.valueOf((int) coord) + "/1";

		return output;
	}

	private void FillPhotoList()
	{
		// initialize the list!
		galleryList.clear();

		String[] projection = { MediaStore.Images.ImageColumns.DISPLAY_NAME };
		// intialize the Uri and the Cursor, and the current expected size.
		Cursor c = null;
		Uri u = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
		//
		// Query the Uri to get the data path. Only if the Uri is valid.
		if (u != null) {
			c = managedQuery(u, projection, null, null, null);
		}

		// If we found the cursor and found a record in it (we also have the
		// id).
		if ((c != null) && (c.moveToFirst())) {
			do {
				// Loop each and add to the list.
				galleryList.add(c.getString(0));
			} while (c.moveToNext());
		}
	}

	public void onLocationChanged(Location location)
	{
		if (location != null) {
			latDMS = decimalToDMS(location.getLatitude());
			lngDMS = decimalToDMS(location.getLongitude());

		}
	}

	public void onProviderDisabled(String arg0)
	{
		// TODO Auto-generated method stub

	}

	public void onProviderEnabled(String arg0)
	{
		// TODO Auto-generated method stub

	}

	public void onStatusChanged(String arg0, int arg1, Bundle arg2)
	{
		// TODO Auto-generated method stub

	}
}
